/*!
 * Copyright &copy; 2013-2015 山东易科德软件有限公司   All rights reserved.
 * 
 * 通用公共方法
 * @author ThinkGem
 * @version 2014-5-31
 */

/**
 * 页面初始化
 */
$(document).ready(function() {
	// 链接去掉虚框
	$("a").bind("focus",function() {
		if(this.blur) this.blur();
	});
	// 单击空白关闭tab右键菜单
	$(document).click(function(){
		top.$(".div_RightMenu").hide();
	});
	// 初始化Metronic组件
	if (typeof Metronic != 'undefined'){
		Metronic.init();
	}
	// 所有下拉框使用select2
	if (window.Select2 !== undefined){
		$("select:not(.noselect2)").select2().on('change', function(){
			try { $(this).valid(); }catch(e){}
		});
	}
	// 默认第一个可用输入框获得焦点
	$("input[type=text]:not([readonly]):not([disabled]):eq(0)").focus();
	// 自动高度元素加载完成后自动显示
	$(".autoHeight").show();
	// 实现IE8或IE9的placeholder效果修正
	if (!! navigator.userAgent.match(/MSIE 8.0/) || !! navigator.userAgent.match(/MSIE 9.0/)) {
    	setTimeout(function(){
    		$('input[placeholder],textarea[placeholder]').placeholder();
    	}, 500);
	}
//	// 斑马风格表单
//	$(".table-form tr").each(function(i,e){
//		$(e).addClass(i%2!=0?"odd":"even");
//	});
	// 文本域自动高度
	$(".table-form textarea").textareaAutoHieght();
});

/**
 * JS 全局常量定义
 */
var Oper = {
	// 新增
	ADD: "Add", 
	// 修改
	EDIT: "Edit",
	// 删除
	DELETE: "Delete",
	// 停用
	DISABLE: "Disable",
	// 启用
	ENABLE: "Enable",
	// 赋权
	GRANT: "Grant",
	//审批
	APPROV:"Approv",
	// 角色信息
	// 省公司
	ROLE_PROV: "roleProv",
	// 分公司
	ROLE_BRAN: "roleBran",
	// 加油站
	ROLE_STAT: "roleStat"
};

/**
 * 获得jBox对话框对象
 */
function getJBox(){
	var $jBox = undefined;
	if (top.$ && top.$.jBox){
		$jBox = top.$.jBox;
	}else if (parent.$ && parent.$.jBox){
		$jBox = parent.$.jBox;
	}else if ($ && $.jBox){
		$jBox = $.jBox;
	}
	return $jBox;
}

/**
 * 引入js和css文件 include('ckeditorLib','${ctxStatic}/ckeditor/',['ckeditor.js']);
 * @deprecated to loadFile(file, callback, error);
 */
function include(id, path, file){
	if (document.getElementById(id)==null){
        var files = typeof file == "string" ? [file] : file;
        for (var i = 0; i < files.length; i++){
            var name = files[i].replace(/^\s|\s$/g, "");
            var att = name.split('.');
            var ext = att[att.length - 1].toLowerCase();
            var isCSS = ext == "css";
            var tag = isCSS ? "link" : "script";
            var attr = isCSS ? " type='text/css' rel='stylesheet' " : " type='text/javascript' ";
            var link = (isCSS ? "href" : "src") + "='" + path + name + "'";
            document.write("<" + tag + (i==0?" id="+id:"") + attr + link + "></" + tag + ">");
        }
	}
}

/**
 * 异步加载文件，loadFile v1.0
 * loadFile(file文件路径, callback成功回调, error失败回调)
 * loadFile('js/test1.js',function(){},function(data){});
 * loadFile(['js/test1.js','js/test2.js'],function(){},function(data){});
*/
function loadFile(file, callback, error) {
	callback = callback || function() {};
	error = error || function() {};
	var getHashCode = function(str, caseSensitive) {
		if (!caseSensitive) {
			str = str.toLowerCase();
		}
		var hash = 1315423911, i, ch;
		for (i = str.length - 1; i >= 0; i--) {
			ch = str.charCodeAt(i);
			hash ^= ((hash << 5) + ch + (hash >> 2));
		}
		return (hash & 0x7FFFFFFF);
	}
	var htmlDoc = document.getElementsByTagName('head')[0],
		okCounts = 0, fileCounts = 0, i,loadFilePath=null;
	var files = typeof file == "string" ? [file] : file;
	fileCounts = files.length;
	for (i = 0; i < fileCounts; i++) {
		var includeFile = null,
			att = null, ext, hash;
		loadFilePath=files[i];
		hash = getHashCode(loadFilePath);
		if (document.getElementById("loadHash_" + hash)) {
			//console.log(loadFilePath + ' ready fired');
			okCounts += 1;
			if (okCounts == fileCounts) {
				callback();
			}
			continue;
		}
		att = loadFilePath.split('?')[0].split('.');
		ext = att[att.length - 1].toLowerCase();
		switch (ext) {
		case 'css':
			includeFile = document.createElement('link');
			includeFile.setAttribute('rel', 'stylesheet');
			includeFile.setAttribute('type', 'text/css');
			includeFile.setAttribute('href', loadFilePath);
			break;
		case 'js':
			includeFile = document.createElement('script');
			includeFile.setAttribute('type', 'text/javascript');
			includeFile.setAttribute('src', loadFilePath);
			break;
		case 'jpg':
		case 'jpeg':
		case 'png':
		case 'gif':
			includeFile = document.createElement("img");
			includeFile.setAttribute('src', loadFilePath);
			break;
		default:
			error('载入的格式不支持:' + loadFilePath);
			//console.log('载入的格式不支持:' + loadFilePath);
			return false;
		}
		if (typeof includeFile != "undefined") {
			includeFile.setAttribute('id', "loadHash_" + hash);
			htmlDoc.appendChild(includeFile);
			includeFile.onreadystatechange = function() {
				if (includeFile.readyState == 'loaded' || includeFile.readyState == 'complete') {
					//console.log(includeFile.id + ' onreadystatechange fired');
					okCounts += 1;
					if (okCounts == fileCounts) {
						callback();
					}
				}
			}
			includeFile.onload = function() {
				//console.log(includeFile.id + ' onload fired');
				okCounts += 1;
				if (okCounts == fileCounts) {
					callback();
				}
			}
			includeFile.onerror = function() {
				$("#loadhash_" + hash).remove();
				//console.log(loadFilePath + 'load error');
				error(loadFilePath + ' load error');
				return false;
			}
		} else {
			error('文件创建失败');
			return false;
		}
	}
	return true;
}

/**
 * 获取URL地址参数
 */
function getQueryString(paramName, url) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)", "i");
    if (!url || url == ""){
	    url = window.location.search;
    }else{	
    	url = url.substring(url.indexOf("?"));
    }
    r = url.substr(1).match(reg)
    if (r != null) {
    	return unescape(r[2]); 
    }
    return null;
}

/**
 * 获取字典标签
 */
function getDictLabel(data, value, defaultValue, inCss){
	var result = [];
	for (var i=0; i<data.length; i++){
		var row = data[i];
//		if (row.value == value){
		if ((','+value+',').indexOf(','+row.value+',') != -1){
			var str = '';
			if (inCss && (row.cssClass || row.cssStyle)){
				str += '<span';
				if (row.cssClass){
					str += ' class="'+row.cssClass+'"';
				}
				if (row.cssStyle){
					str += ' style="'+row.cssStyle+'"';
				}
				result.push(str + '>' + row.label + '</span>');
			}else{
				result.push(row.label);
			}
		}
	}
	return result.length > 0 ? result.join(',') : defaultValue;
}

/**
 * 打开一个Window窗体
 */
function windowOpen(url, name, width, height){
	var top=parseInt((window.screen.height-height)/2,10),left=parseInt((window.screen.width-width)/2,10),
		options="location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,"+
		"resizable=yes,scrollbars=yes,"+"width="+width+",height="+height+",top="+top+",left="+left;
	window.open(url ,name , options);
}

/**
 * 关闭当前Window窗体
 */
function windowClose(){
	setTimeout(function(){
		window.opener = null;
		window.open('','_self');
		window.close();
	}, 100);
} 

/**
 * 显示加载框
 * @param message
 */
function loading(message){
	
	// 调用最上级加载消息框
	top.loadingFlag = true; // 防止递归调用
	var method = top.loading || parent.parent.loading || parent.loading;
	if (typeof loadingFlag == 'undefined' && method && typeof method == 'function'){
		method(message);
		return;
	}
	
	// 设置默认消息
	if (message == undefined || message == ""){
		message = "正在加载，请稍后...";
	}
	if (message == 'none'){
		return;
	}
	resetTip();

	setTimeout(function(){
		// 页面加载提示框数（已加载的不重复显示）
		if (!$.pageLoadingNum){
			$.pageLoadingNum = 0;
		}
		
		if ($('#page-loading').length == 0){
	        $('body').append('<div id="page-loading" class="page-loading">' + message + '</div>');
		}
		$('#page-loading span').text(message);
		
		// 顶部进度条加载
		if ($('#page-loading-top').length == 0){
	    	$('body').append('<div id="page-loading-top" class="page-loading-top"></div>');
	    	$('#page-loading-top').animate({width:"65%"}, 2000, function(){
	    		$(this).animate({width:"85%"}, 8000);
	    	});
		}
		$.pageLoadingNum++;
//		log("loading num: " + $.pageLoadingNum);
	}, 0);
}

/**
 * 关闭加载框
 */
function closeLoading(timeout, forceClose){

	// 调用最上级加载消息框
	top.closeLoadingFlag = true; // 防止递归调用
	var method = top.closeLoading || parent.parent.closeLoading || parent.closeLoading;
	if (typeof closeLoadingFlag == 'undefined' && method && typeof method == 'function'){
		method(timeout, forceClose);
		return;
	}
	
	setTimeout(function(){
		if (!$.pageLoadingNum){
			$.pageLoadingNum = 0;
		}
//		log("closeLoading num: " + $.pageLoadingNum);
		$.pageLoadingNum--;
		if (forceClose || $.pageLoadingNum <= 0){
			$('#page-loading').remove();
			
			// 顶部进度条停止
	    	$("#page-loading-top").stop().animate({width:"100%"}, 200, function(){
	    		$(this).fadeOut(300, function(){
	    			$(this).remove();
	    		});
	    	});
	    	$.pageLoadingNum = 0;
		}
	}, timeout == undefined ? 0 : timeout);
}

/**
 * 显示提示框
 * @deprecated showMessage(message, title, type, timeout)
 */
function showTip(message, type, timeout, lazytime){
	var $jBox = getJBox();
	if (!$jBox){
		return;
	}
	resetTip();
	setTimeout(function(){
		$jBox.tip(message, (type == undefined || type == '' ? 'info' : type), {opacity:0, 
			timeout:  timeout == undefined ? 2000 : timeout});
	}, lazytime == undefined ? 500 : lazytime);
}

/**
 * 关闭提示框
 * @deprecated closeMessage()
 */
function closeTip(){
	var $jBox = getJBox();
	if (!$jBox){
		return;
	}
	$jBox.closeTip();
}

/**
 * 恢复提示框显示
 * @deprecated closeMessage()
 */
function resetTip(){
	var $jBox = getJBox();
	if (!$jBox){
		return;
	}
	$jBox.tip.mess = null;
}

/**
 * 显示提示框
 */
function showMessage(message, title, type, timeout){
	resetTip();
	
	var msgType;
	if (type == undefined || type == ''){
		if (message.indexOf('成功') >= 0){
			msgType = 'success';
		}else if (message.indexOf('不能') >= 0 || message.indexOf('不允许') >= 0
				|| message.indexOf('必须') >= 0|| message.indexOf('已存在') >= 0){
			msgType = 'warning';
		}else if (message.indexOf('错误') >= 0 || message.indexOf('失败') >= 0){
			msgType = 'error';
		}else{
			msgType = 'info';
		}
	}else{
		msgType = type;
	}

	var msgTimeout = timeout == undefined ? 4000 : timeout;
	
	if (!top.toastr){
		var $jBox = getJBox();
		if (!$jBox){
			alert(message);
			return;
		}
		$jBox.tip(message, msgType, {opacity:0, timeout: msgTimeout});
		return;
	}
	
	var positionClass = "toast-bottom-right";
	if (message && message.length >= 8 && message.indexOf('posfull:') >= 0){
		positionClass = "toast-top-full-width";
		message = message.substring(8);
	}
	
	top.toastr.options = {
		"closeButton": true,
		"positionClass": positionClass,
		"timeOut": msgTimeout
	}
	top.toastr[msgType](message, title);
}

/**
 * 关闭提示框
 */
function closeMessage(){
	if (!top.toastr){
		return;
	}
	top.toastr.clear();
}

/**
 * 提示对话框
 */
function alertx(message, closed){
	var $jBox = getJBox();
	if (!$jBox){
		alert(message);
		if (typeof closed == 'function') {
			closed();
		}
		return;
	}
	$jBox.info(message, '提示', {closed:function(){
		if (typeof closed == 'function') {
			closed();
		}
	}});
}

/**
 * 确认对话框
 */
function confirmx(message, urlOrFun, data, callback, dataType, async, loadingMessage){
	// 如果data为函数，则后面的参数往前移
	if (typeof data == 'function') {
		loadingMessage = async;
		async = dataType;
		dataType = callback;
		callback = data;
		data = undefined;
	}
	var $jBox = getJBox();
	if (!$jBox){
		if (confirm(message)){
			if (typeof urlOrFun == 'function') {
				urlOrFun();
			}else{
				if (callback == undefined && dataType == undefined) {
					resetTip();
					location = urlOrFun;
				}else{
					$.ajax({
						type: 'POST',
						url: urlOrFun,
						data: data,
						dataType: dataType == undefined ? 'json' : dataType,
						async: async == undefined ? true : async,
						error: function(data){
							if (data.responseText && data.responseText != ''){
								showMessage('操作失败，' + data.responseText + '！');
							}
						},
						success: function(data){
							if (typeof callback == 'function') {
								callback(data);
							}
						}
					});
				}
			}
		}
		return;
	}
	$jBox.confirm(message,'系统提示',function(v,h,f){
		if(v=='ok'){
			if (typeof urlOrFun == 'function') {
				urlOrFun();
			}else{
				// 如果没有回调，则直接重定向指定页面
				if (callback == undefined && dataType == undefined) {
					resetTip();
					location = urlOrFun;
				}else{
					loading(loadingMessage == undefined ? '正在执行，请稍后...' : loadingMessage);
					$.ajax({
						type: 'POST',
						url: urlOrFun,
						data: data,
						dataType: dataType == undefined ? 'json' : dataType,
						async: async == undefined ? true : async,
						error: function(data){
							if (data.responseText && data.responseText != ''){
								showMessage('操作失败，' + data.responseText + '！');
							}
							closeLoading(0, true);
						},
						success: function(data){
							if (typeof callback == 'function') {
								callback(data);
							}
							closeLoading();
						}
					});
				}
			}
		}
	},{buttonsFocus:1, closed:function(){
		if (typeof callback == 'function' && dataType == undefined) {
			callback();
		}
	}});
	return false;
}

/**
 * 提示输入对话框
 */
function promptx(title, lable, urlOrFun, closed){
	var $jBox = getJBox();
	if (!$jBox){
		var value = prompt(title + ': ' + label);
		if (value != null && value != ""){
			if (typeof urlOrFun == 'function') {
				urlOrFun(value);
			}else{
				location = urlOrFun + encodeURIComponent(f.txt);
			}
		}
		if (typeof closed == 'function') {
			closed(value);
		}
		return;
	}
	$jBox("<div class='form-search' style='padding:20px;text-align:center;'>" + lable + "：<input type='text' id='txt' name='txt'/></div>", {
			title: title, submit: function (v, h, f){
	    if (f.txt == '') {
	    	showMessage("请输入" + lable + "。", 'error');
	        return false;
	    }
		if (typeof urlOrFun == 'function') {
			urlOrFun(f.txt);
		}else{
			resetTip(); //loading();
			location = urlOrFun + encodeURIComponent(f.txt);
		}
	},closed:function(){
		if (typeof closed == 'function') {
			closed();
		}
	}});
	return false;
}

/**
 * 添加TAB页面
 * @param $this 		点击的对象
 * @param title 		提示标题
 * @param url   		访问的路径
 * @param parentTabPageId 来源页面ID
 * @param closeable	 	是否有关闭按钮
 * @param refresh 		打开后是否刷新重新加载
 */
function addTabPage($this, title, url, parentTabPageId, closeable, refresh){
	top.addTabPageFlag = true; // 防止递归调用
	var method = top.addTabPage || parent.parent.addTabPage || parent.addTabPage;
	if (typeof addTabPageFlag != 'undefined' || !method || typeof method != 'function'){
		windowOpen(url, title, 'auto', 'auto');
		return;
	}
	method($this, title, url, parentTabPageId, closeable, refresh);
}

/**
 * 关闭当前TAB页面，并激活上级页面
 * @param parentTabPageId 上级界面ID
 * @param callback(contents, contentWindow)	关闭时的回调方法，传入上级页面的contents和contentWindow
 */
function closeCurrentTabPage(parentTabPageId, callback){
	top.closeCurrentTabPageFlag = true; // 防止递归调用
	var method = top.closeCurrentTabPage || parent.parent.closeCurrentTabPage || parent.closeCurrentTabPage;
	if (typeof closeCurrentTabPageFlag != 'undefined' || !method || typeof method != 'function'){
		windowClose();
		return;
	}
	method(parentTabPageId, callback);
}

/**
 * AJAX 提交
 */
function ajaxSubmit(url, data, callback, dataType, async, message){
	loading(message == undefined ? '正在执行，请稍后...' : message);
	$('.btn').attr("disabled", true); // 提交表单时禁用按钮，防止重复提交。
	// 如果data为函数，则后面的参数往前移
	if (typeof data == 'function') {
		message = async;
		async = dataType;
		dataType = callback;
		callback = data;
		data = undefined;
	}
	$.ajax({
		type: 'POST',
		url: url,
		data: data,
		dataType: dataType == undefined ? 'json' : dataType,
		async: async == undefined ? true : async,
		error: function(data){
			$('.btn').attr("disabled", false);
			if (data.responseText && data.responseText != ''){
				showMessage('操作失败，' + data.responseText + '！');
			}
			closeLoading(0, true);
		},
		success: function(data){
			$('.btn').attr("disabled", false);
			closeLoading();
			if (typeof callback == 'function') {
				callback(data);
			}
		}
	});
}

/**
 * AJAX 提交表单
 */
function ajaxSubmitForm(formJqueryObj, callback, dataType, async, message){
	var url = formJqueryObj.attr("action");
	var data = formJqueryObj.serializeArray();
	ajaxSubmit(url, data, callback, dataType, async, message);
}

/**
 * cookie 操作
 * 	1、不写value表示获取cookie
 * 	2、value设置为null表示删除cookie
 *  3、options:{expires:7} 如果是数字，则expires单位为天。
 */
function cookie(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
}

/**
 * 获取一个值，复杂类型或嵌套类型时，取不到属性中的属性时不抛出异常
 * 调用示例：getVal(jsonData, 'user.office.name');
 */
function getVal(jsonObj, attrName) {
	if(jsonObj===undefined) {
		return '';
	}
	var ret,p,prm = [], i;
	if( typeof attrName === 'function') { return attrName(jsonObj); }
	ret = jsonObj[attrName];
	if(ret===undefined) {
		try {
			if ( typeof attrName === 'string' ) {
				prm = attrName.split('.');
			}
			i = prm.length;
			if( i ) {
				ret = jsonObj;
				while (ret && i--) {
					p = prm.shift();
					ret = ret[p];
				}
			}
		} catch (e) {}
	}
	if(ret===undefined) {
		return '';
	}
	return ret;
}

/**
 * 数值前补零
 */
function pad(num, n) {
    var len = num.toString().length;
    while(len < n) {
        num = "0" + num;
        len++;
    }
    return num;
}

/**
 * String的startWith
 */
String.prototype.startWith=function(str){ 
    var reg = new RegExp("^"+str); 
    return reg.test(this); 
}

/**
 * String的endWith
 */
String.prototype.endWith=function(str){ 
    var reg = new RegExp(str+"$"); 
    return reg.test(this); 
} 

/**
 * 日期格式化扩展
 */
Date.prototype.format = function(f){
    var o ={
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(),    //day
        "h+" : this.getHours(),   //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
        "S" : this.getMilliseconds() //millisecond
    }
    if(/(y+)/.test(f))f=f.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(f))f = f.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));return f
}

/**
 * 日期转为字符串
 * @param date
 * @returns
 */
function dateToStr(date){
	return date.format("yyyy-MM-dd hh:mm:ss");
}

/**
 * 字符串转为日期
 * @param date
 * @returns {Date}
 */
function strToDate(date){
	return new Date(date.replace(/-/g,"/"));
}

/**
 * 日期加减
 * @param date
 * @param dadd
 * @returns {Date}
 */
function addDate(date, dadd){  
	date = date.valueOf();
	date = date + dadd * 24 * 60 * 60 * 1000;
	return new Date(date);  
}

/**
 * 获取某天后的日期数据
 * @param addDay 增加的天数，向后计算为正数，向后计算为负数
 * @returns JSON object
 * 	param.y	 	= 年[数值型]
 * 	param.m	 	= 月[数值型]
 * 	param.d	 	= 日[数值型]
 * 	param.year 	= 年[字符串型YYYY]
 * 	param.month 	= 月[字符串型MM]
 * 	param.day 	= 日[字符串型DD]
 * 	param.date 	= 年月日[字符串型YYYYMMDD]
 */
function getDay(addDay){
	if(addDay == null || addDay == undefined || addDay == ''){
		addDay = 0;
	}
	var dd = new Date();
	dd.setDate(dd.getDate()+addDay);//获取AddDayCount天后的日期
	
	// 数值型
	var y = dd.getFullYear();
	var m = dd.getMonth()+1;//获取当前月份的日期
	var d = dd.getDate();
	// 字符串型，一位前补零
	var year = y+''; // 如2014
	var month = m+''; // 如07
	var day = d+''; // 如03
	var date = ''; // 如20140703
 
	// 月，日补零
	if(m<10){
		month = "0"+m;
	}
	if(d<10){
		day = "0"+d;
	}
	// 计算日期，年月日
	date = year + month + day;
	
	// 设置参数
	var param = new Object();
	param.y 	= y;
	param.m 	= m;
	param.d 	= d;
	param.year 	= year;
	param.month = month;
	param.day 	= day;
	param.date 	= date;

	return param;
}

/**
 * 查询当前是第几个周
 * @param date
 */
function getWeekOfYear(date) {
	// 定义变量d为当年的1月1日0点
	var d = new Date();
	d.setFullYear(d.getFullYear(),0,1);
	// 定义day为当年1月1日的星期数(0为星期天,1为星期1,6为星期6)
	var day = d.getDay();
	// 定义fistweekleft为第一周剩余的天数,此处认为星期一是一周的第一天，如果将星期天定义为一周的第一天，请写成fistweekleft = (6-day)%6
	var fistweekleft = (7-day)%7;
	// 将d赋值为第二周的第一天,1+fistweekleft号为第一周最后天，1+fistweekleft+1为第二周第一天
	d.setFullYear(d.getFullYear(),0,1+fistweekleft+1);
	// 定义变量d1为当天
	var d1 = new Date();
	// 当前时间与当年第二周第一天的毫秒数之差除以一周的毫秒数并取整即为当前日期距本的第二周已过的周数
	// 结果加上2即为当天为本年的第几周（如果在一周的第一天的0点运行此程序，结果会比实际值大1，此种情况请自行处理）
	return (2+parseInt((d1.getTime()-d.getTime())/1000/60/60/24/7));
}

/**
 * 快速选择日期方法
 * @param type 1今日，2本周，3本月，4本季度，5上月
 * @param beginDateId endDateId 开始和结束日期控件的ID
 */
function quickSelectDate(type, beginDateId, endDateId){
	
	var now = new Date(), 		//当前日期 
	nowYear = now.getFullYear(),//当前年 
	nowMonth = now.getMonth(), 	//当前月 
	nowDay = now.getDate(), 	//当前日 
	nowDayOfWeek = now.getDay(),//今天本周的第几天 
	
	beginDate = $('#'+beginDateId), // 开始日期控件
	endDate = $('#'+endDateId), // 结束日期控件
	
	// 格式化日期 yyyy-MM-dd 
	formatDate = function(date) {
		return date.format("yyyy-MM-dd");
	},

	// 获得某月的天数 
	getMonthDays = function(myMonth) {
		var monthStartDate = new Date(nowYear, myMonth, 1);
		var monthEndDate = new Date(nowYear, myMonth + 1, 1);
		var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
		return days;
	};

	// 今日
	if (type == '1'){
		beginDate.val(formatDate(now));
		endDate.val(beginDate.val());
	}
	// 本周
	else if(type == '2'){
		var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
		var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek + 1));
		beginDate.val(formatDate(weekStartDate));
		endDate.val(formatDate(weekEndDate));
	}
	// 本月
	else if(type == '3'){
		var monthStartDate = new Date(nowYear, nowMonth, 1);
		var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
		beginDate.val(formatDate(monthStartDate));
		endDate.val(formatDate(monthEndDate));
	}
	// 本季度
	else if(type == '4'){
		var quarterStartMonth = 0; // 本季度的开始月份 
		if (nowMonth < 3) {
			quarterStartMonth = 0;
		}
		if (2 < nowMonth && nowMonth < 6) {
			quarterStartMonth = 3;
		}
		if (5 < nowMonth && nowMonth < 9) {
			quarterStartMonth = 6;
		}
		if (nowMonth > 8) {
			quarterStartMonth = 9;
		}
		var quarterEndMonth = quarterStartMonth + 2; // 本季度结束月份
		var quarterStartDate = new Date(nowYear, quarterStartMonth, 1);
		var quarterEndDate = new Date(nowYear, quarterEndMonth, getMonthDays(quarterEndMonth));
		beginDate.val(formatDate(quarterStartDate));
		endDate.val(formatDate(quarterEndDate));
	}
	// 上月
	else if(type == '5'){
		var lastMonthDate = new Date(); //上月日期 
			lastMonthDate.setDate(1);
			lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
		var lastYear = lastMonthDate.getYear();
		var lastMonth = lastMonthDate.getMonth();
		var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
		var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
		beginDate.val(formatDate(lastMonthStartDate));
		endDate.val(formatDate(lastMonthEndDate));
	}
	// 触发onchange事件
	beginDate.change();
	endDate.change();
}

/**
 * 日期选择控件（用法见：dateselect.tag）
 */
(function($){
	$.fn.dateselect = function (options) {
		
		var inputDate = $(this),
			selYear = options.selYear,
			selMonth = options.selMonth,
			selDay = options.selDay,
			minYear = options.minYear,
			maxYear = options.maxYear;
	
		initDate();
		refreshDate();
		
		/** 
		 * 初始化日期控件
		 */
		function initDate(){
			
			var year = new Date().getFullYear();
			var range = [
	             maxYear > 0 ? maxYear : year,
	             minYear > 0 ? minYear : year - 80
	        ];
			addOpt(selYear, range);
			addOpt(selMonth, [1,12]);
			
			selYear.change(function(e) {
				setDay(selYear.val(), selMonth.val());
				setDate();
			});
	
			if (selMonth.size() > 0){
				selMonth.change(function(e) {
					setDay(selYear.val(), selMonth.val());
					setDate();
				});
			}
			
			if (selDay.size() > 0){
				selDay.change(function(e) {
					setDate();
				});
			}
			
			inputDate.change(function(e) {
				refreshDate();
			});
		}
		
		/** 
		 * 初始化选择值
		 */
		function refreshDate(){
			if (inputDate.val() != ''){
				var ss = inputDate.val().split('-');
				if (ss[0] != undefined){
					selYear.val(ss[0]);
				}
				if (ss[1] != undefined && selMonth.size() > 0){
					selMonth.val(ss[1]);
					setDay(selYear.val(), selMonth.val());
				}
				if (ss[2] != undefined && selDay.size() > 0){
					selDay.val(ss[2]);
				}
				if (window.Select2 !== undefined) {
					selYear.select2();
					selMonth.select2();
					selDay.select2();
				}
			}
		}
		
		/** 
		 * 刷新日期隐藏域控件
		 */
		function setDate(){
			var val = '';
			if (selYear.val() != '年'){
				val += selYear.val();
				if (selMonth.size() > 0 && selMonth.val() != '月'){
					val += '-' + selMonth.val();
					if (selDay.size() > 0 && selDay.val() != '日'){
						val += '-' + selDay.val();
					}
				}
			}
			inputDate.val(val);
		}
		
		/** 
		 * 刷新“日”下拉框
		 */ 
		function setDay(year, month){//m为改变的月份值  
			if (selDay.size() == 0){
				return;
			}
			selDay.empty().html('<option>日</option>');
			var day = 0; 
			if(year!='年' && month!='月'){ 
				year = parseInt(year);
				month = parseInt(month);
				if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12 ){
					day = 31;
				}else if(month==4 || month==6 || month==9 || month==11){
					day = 30;
				}else{
					if ((year%4==0 && year%100!=0) || (year%400==0)){
						day = 29; //闰年公式，判断是否为闰年  
					}else{
						day = 28;
					}
				}
				addOpt(selDay,[1,day])
			}
			if (window.Select2 !== undefined) {
				selDay.select2();
			}
		}
		
		/** 
		 * 给下拉框添加选项
		 */ 
		function addOpt(box, range){
			if(range[1]>=range[0]){
				for(var i=range[0]; i<=range[1]; i++){
					var val = i <= 9 ? '0'+i : i;
					var opt=$('<option></option>').attr({value:val}).text(val).appendTo(box);
				}
			}else{
				for(var i=range[0]; i>=range[1]; i--){
					var val = i <= 9 ? '0'+i : i;
					var opt=$('<option></option>').attr({value:i}).text(i).appendTo(box);
				}
			}
		}
		
	};
	
})(jQuery);

/**
 * 截取字符串，区别汉字和英文
 */
function abbr(name, maxLength){  
    if(!maxLength){  
        maxLength = 20;  
    }  
    if(name==null||name.length<1){  
        return "";  
    }  
    var w = 0;//字符串长度，一个汉字长度为2   
    var s = 0;//汉字个数   
    var p = false;//判断字符串当前循环的前一个字符是否为汉字   
    var b = false;//判断字符串当前循环的字符是否为汉字   
    var nameSub;  
    for (var i=0; i<name.length; i++) {  
       if(i>1 && b==false){  
            p = false;  
       }  
       if(i>1 && b==true){  
            p = true;  
       }  
       var c = name.charCodeAt(i);  
       //单字节加1   
       if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {  
            w++;  
            b = false;  
       }else {  
            w+=2;  
            s++;  
            b = true;  
       }  
       if(w>maxLength && i<=name.length-1){  
            if(b==true && p==true){  
                nameSub = name.substring(0,i-2)+"...";  
            }  
            if(b==false && p==false){  
                nameSub = name.substring(0,i-3)+"...";  
            }  
            if(b==true && p==false){  
                nameSub = name.substring(0,i-2)+"...";  
            }  
            if(p==true){  
                nameSub = name.substring(0,i-2)+"...";  
            }  
            break;  
       }  
    }  
    if(w<=maxLength){  
        return name;  
    }  
    return nameSub;  
}

/**
 * 金额格式化（千位符，小数四舍五入）金额每隔三位加一个逗号
 */
function moneyFormat(s, n) {
	if (s == undefined || s == ''){
		return '0.00';
	}
	n = n > 0 && n <= 20 ? n : 2;
	s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
	var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
	t = "";
	for (i = 0; i < l.length; i++) {
		t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
	}
	return t.split("").reverse().join("") + "." + r; 
}

/**
 * 格式化数值
 * @param num 待格式化的树
 * @param cent 保留小数位数
 * @param isThousand 是否进行千分位格式化
 */
function formatNumber(num, cent, isThousand) {
	num = num.toString().replace(/\$|\,/g, '');
	// 检查传入数值为数值类型
	if (isNaN(num))
		num = "0";
	// 获取符号(正/负数)
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * Math.pow(10, cent) + 0.50000000001); // 把指定的小数位先转换成整数.多余的小数位四舍五入
	cents = num % Math.pow(10, cent); // 求出小数位数值
	num = Math.floor(num / Math.pow(10, cent)).toString(); // 求出整数位数值
	cents = cents.toString(); // 把小数位转换成字符串,以便求小数位长度
	// 补足小数位到指定的位数
	while (cents.length < cent)
		cents = "0" + cents;
	if (isThousand) {
		// 对整数部分进行千分位格式化.
		for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
			num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
	}
	if (cent > 0)
		return (((sign) ? '' : '-') + num + '.' + cents);
	else
		return (((sign) ? '' : '-') + num);
}

/**
 * 输出js日志
 */
function Log(){}
var LogLevel={
	DEBUG:0,INFO:1
	// ,WARN:2,ERROR:3,FATAL:4
};
var logLevel = LogLevel.DEBUG;
function showLogMsg(msg,obj){
	if(typeof(console) !== 'undefined'){console.log(msg);}
}
Log.debug=function(msg,obj){
	if(logLevel<=LogLevel.DEBUG){showLogMsg(msg,obj);}
}
Log.info=function(msg,obj){
	if(logLevel<=LogLevel.INFO){showLogMsg(msg,obj);}
}
Log.log=function(msg,obj){
	Log.debug(msg,obj);
}
function log(msg){
	Log.log(msg);
}

/**
 * 跳转到特定JSP页面，不做业务处理
 * @param $this 		点击的对象
 * @param title 		提示标题
 * @param jsp   		跳转的jsp页面
 * @param param			跳转到JSP时传递的参数JSON对象
 */
function redirectJSP($this,title,jsp,param){
	var redirectJsp = "";
	var url = ctx+"/sys/redirect";
	// jsp
	url = url + "?redirectJSP="+jsp;
	// param
	param = (param == undefined ? {} : param);
	if(typeof(param)!="object"){
		Log.log('type is text.now parsing....');
		param = JSON.parse(param);
	}
	for(var o in param){  
	  url += "&"+o+"="+param[o];
	} 
	Log.log(url);
	
	addTabPage($this, title, url, tabPageId);
}

/**
 * 线程堵塞，等待几毫秒后再执行
 */
function sleep(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

/**
 * 根据js模板生成代码，使用Mustache.js引擎
 */
function template(tplId, data, partials){
	return templateRender(getTemplateData(tplId), data, partials);
}

/**
 * 根据script标签的id，获取模板数据，自动替换 //<!-- //--> 的内容
 */
function getTemplateData(tplId){
	return String($("#"+tplId).html()).replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
}

/**
 * 根据js模板生成代码，使用Mustache.js引擎，调用render方法
 */
function templateRender(template, data, partials){
	return Mustache.render(template, data, partials);
}

/**
 * Mustache js - Logic-less {{mustache}} templates with JavaScript
 * http://github.com/janl/mustache.js  V2.2.0
 */
(function(global,factory){if(typeof exports==="object"&&exports){factory(exports)}else if(typeof define==="function"&&define.amd){define(["exports"],factory)}else{factory(global.Mustache={})}})(this,function(mustache){var Object_toString=Object.prototype.toString;var isArray=Array.isArray||function(object){return Object_toString.call(object)==="[object Array]"};function isFunction(object){return typeof object==="function"}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var RegExp_test=RegExp.prototype.test;function testRegExp(re,string){return RegExp_test.call(re,string)}var nonSpaceRe=/\S/;function isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};function escapeHtml(string){return String(string).replace(/[&<>"'\/]/g,function(s){return entityMap[s]})}var whiteRe=/\s*/;var spaceRe=/\s+/;var equalsRe=/\s*=/;var curlyRe=/\s*\}/;var tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var sections=[];var tokens=[];var spaces=[];var hasTag=false;var nonSpace=false;function stripSpace(){if(hasTag&&!nonSpace){while(spaces.length)delete tokens[spaces.pop()]}else{spaces=[]}hasTag=false;nonSpace=false}var openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tags){if(typeof tags==="string")tags=tags.split(spaceRe,2);if(!isArray(tags)||tags.length!==2)throw new Error("Invalid tags: "+tags);openingTagRe=new RegExp(escapeRegExp(tags[0])+"\\s*");closingTagRe=new RegExp("\\s*"+escapeRegExp(tags[1]));closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tags[1]))}compileTags(tags||mustache.tags);var scanner=new Scanner(template);var start,type,value,chr,token,openSection;while(!scanner.eos()){start=scanner.pos;value=scanner.scanUntil(openingTagRe);if(value){for(var i=0,valueLength=value.length;i<valueLength;++i){chr=value.charAt(i);if(isWhitespace(chr)){spaces.push(tokens.length)}else{nonSpace=true}tokens.push(["text",chr,start,start+1]);start+=1;if(chr==="\n")stripSpace()}}if(!scanner.scan(openingTagRe))break;hasTag=true;type=scanner.scan(tagRe)||"name";scanner.scan(whiteRe);if(type==="="){value=scanner.scanUntil(equalsRe);scanner.scan(equalsRe);scanner.scanUntil(closingTagRe)}else if(type==="{"){value=scanner.scanUntil(closingCurlyRe);scanner.scan(curlyRe);scanner.scanUntil(closingTagRe);type="&"}else{value=scanner.scanUntil(closingTagRe)}if(!scanner.scan(closingTagRe))throw new Error("Unclosed tag at "+scanner.pos);token=[type,value,start,scanner.pos];tokens.push(token);if(type==="#"||type==="^"){sections.push(token)}else if(type==="/"){openSection=sections.pop();if(!openSection)throw new Error('Unopened section "'+value+'" at '+start);if(openSection[1]!==value)throw new Error('Unclosed section "'+openSection[1]+'" at '+start)}else if(type==="name"||type==="{"||type==="&"){nonSpace=true}else if(type==="="){compileTags(value)}}openSection=sections.pop();if(openSection)throw new Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function squashTokens(tokens){var squashedTokens=[];var token,lastToken;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];if(token){if(token[0]==="text"&&lastToken&&lastToken[0]==="text"){lastToken[1]+=token[1];lastToken[3]=token[3]}else{squashedTokens.push(token);lastToken=token}}}return squashedTokens}function nestTokens(tokens){var nestedTokens=[];var collector=nestedTokens;var sections=[];var token,section;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];switch(token[0]){case"#":case"^":collector.push(token);sections.push(token);collector=token[4]=[];break;case"/":section=sections.pop();section[5]=token[2];collector=sections.length>0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}}return nestedTokens}function Scanner(string){this.string=string;this.tail=string;this.pos=0}Scanner.prototype.eos=function(){return this.tail===""};Scanner.prototype.scan=function(re){var match=this.tail.match(re);if(!match||match.index!==0)return"";var string=match[0];this.tail=this.tail.substring(string.length);this.pos+=string.length;return string};Scanner.prototype.scanUntil=function(re){var index=this.tail.search(re),match;switch(index){case-1:match=this.tail;this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index);this.tail=this.tail.substring(index)}this.pos+=match.length;return match};function Context(view,parentContext){this.view=view;this.cache={".":this.view};this.parent=parentContext}Context.prototype.push=function(view){return new Context(view,this)};Context.prototype.lookup=function(name){var cache=this.cache;var value;if(name in cache){value=cache[name]}else{var context=this,names,index,lookupHit=false;while(context){if(name.indexOf(".")>0){value=context.view;names=name.split(".");index=0;while(value!=null&&index<names.length){if(index===names.length-1&&value!=null)lookupHit=typeof value==="object"&&value.hasOwnProperty(names[index]);value=value[names[index++]]}}else if(context.view!=null&&typeof context.view==="object"){value=context.view[name];lookupHit=context.view.hasOwnProperty(name)}if(lookupHit)break;context=context.parent}cache[name]=value}if(isFunction(value))value=value.call(this.view);return value};function Writer(){this.cache={}}Writer.prototype.clearCache=function(){this.cache={}};Writer.prototype.parse=function(template,tags){var cache=this.cache;var tokens=cache[template];if(tokens==null)tokens=cache[template]=parseTemplate(template,tags);return tokens};Writer.prototype.render=function(template,view,partials){var tokens=this.parse(template);var context=view instanceof Context?view:new Context(view);return this.renderTokens(tokens,context,partials,template)};Writer.prototype.renderTokens=function(tokens,context,partials,originalTemplate){var buffer="";var token,symbol,value;for(var i=0,numTokens=tokens.length;i<numTokens;++i){value=undefined;token=tokens[i];symbol=token[0];if(symbol==="#")value=this._renderSection(token,context,partials,originalTemplate);else if(symbol==="^")value=this._renderInverted(token,context,partials,originalTemplate);else if(symbol===">")value=this._renderPartial(token,context,partials,originalTemplate);else if(symbol==="&")value=this._unescapedValue(token,context);else if(symbol==="name")value=this._escapedValue(token,context);else if(symbol==="text")value=this._rawValue(token);if(value!==undefined)buffer+=value}return buffer};Writer.prototype._renderSection=function(token,context,partials,originalTemplate){var self=this;var buffer="";var value=context.lookup(token[1]);function subRender(template){return self.render(template,context,partials)}if(!value)return;if(isArray(value)){for(var j=0,valueLength=value.length;j<valueLength;++j){buffer+=this.renderTokens(token[4],context.push(value[j]),partials,originalTemplate)}}else if(typeof value==="object"||typeof value==="string"||typeof value==="number"){buffer+=this.renderTokens(token[4],context.push(value),partials,originalTemplate)}else if(isFunction(value)){if(typeof originalTemplate!=="string")throw new Error("Cannot use higher-order sections without the original template");value=value.call(context.view,originalTemplate.slice(token[3],token[5]),subRender);if(value!=null)buffer+=value}else{buffer+=this.renderTokens(token[4],context,partials,originalTemplate)}return buffer};Writer.prototype._renderInverted=function(token,context,partials,originalTemplate){var value=context.lookup(token[1]);if(!value||isArray(value)&&value.length===0)return this.renderTokens(token[4],context,partials,originalTemplate)};Writer.prototype._renderPartial=function(token,context,partials){if(!partials)return;var value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null)return this.renderTokens(this.parse(value),context,partials,value)};Writer.prototype._unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype._escapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return mustache.escape(value)};Writer.prototype._rawValue=function(token){return token[1]};mustache.name="mustache.js";mustache.version="2.0.0";mustache.tags=["{{","}}"];var defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials){return defaultWriter.render(template,view,partials)};mustache.to_html=function(template,view,partials,send){var result=mustache.render(template,view,partials);if(isFunction(send)){send(result)}else{return result}};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer});

/**
 * EnPlaceholder是一个跨浏览器实现placeholder效果的jQuery插件
 * $('#username2,#password').placeholder({isUseSpan:true});
 */
;(function ($) {
    $.fn.extend({
        "placeholder":function (options) {
            options = $.extend({
                placeholderColor:'#ACA899',
                isUseSpan:true, //是否使用插入span标签模拟placeholder的方式,默认false,默认使用value模拟
                onInput:true,  //使用标签模拟(isUseSpan为true)时，是否绑定onInput事件取代focus/blur事件
                noFixClass:'placeholder-no-fix'// 不placeholder的元素class名称
            }, options);
            $(this).each(function () {
                var _this = this;
                var supportPlaceholder = 'placeholder' in document.createElement('input');
                if (!supportPlaceholder) {
                	if ($(_this).hasClass(options.noFixClass)){
               		    return; // 过滤不进行placeholder的元素
               	 	}
                    var defaultValue = $(_this).attr('placeholder');
                    var defaultColor = $(_this).css('color');
                    if (options.isUseSpan == false) {
                        $(_this).focus(function () {
                            var pattern = new RegExp("^" + defaultValue + "$|^$");
                            pattern.test($(_this).val()) && $(_this).val('').css('color', defaultColor);
                        }).blur(function () {
                                if ($(_this).val() == defaultValue) {
                                    $(_this).css('color', defaultColor);
                                } else if ($(_this).val().length == 0) {
                                    $(_this).val(defaultValue).css('color', options.placeholderColor)
                                }
                            }).trigger('blur');
                    } else {
                   	    var left = "";
                   	    if ($(_this).parent().hasClass('input-group')){
                   		   left = 'left:' + $(_this).position().left + 'px;';
                   	    }
                   	    var widht = $(_this).width() == 0 ? 150 : $(_this).width();
                   	    var height = $(_this).hasClass('input-sm') ? $(_this).height() : $(_this).outerHeight();
                        var $imitate = $('<span class="wrap-placeholder" style="position:absolute;display:inline-block;overflow:hidden;z-index:1000;color:'+options.placeholderColor
                       		 +'; width:' + widht + 'px; height:' + height + 'px;' + left + '">' + defaultValue + '</span>');
                        $imitate.css({
                            'margin-left':$(_this).css('margin-left'),
                            'margin-top':$(_this).css('margin-top'),
                            'font-size':$(_this).css('font-size'),
                            'font-family':$(_this).css('font-family'),
                            'font-weight':$(_this).css('font-weight'),
                            'line-height':_this.nodeName.toLowerCase() == 'textarea' ? $(_this).css('line-weight') : height + 'px',
                            'padding-left':parseInt($(_this).css('padding-left')) + 2 + 'px',
                            'padding-top':_this.nodeName.toLowerCase() == 'textarea' ? parseInt($(_this).css('padding-top')) + 2 : 0
                        });
                        var prev = $(_this).prev();
                        if (prev.hasClass('wrap-placeholder')){
                        	prev.remove(); // 删除已有的
                        }
                        $(_this).before($imitate.click(function () {
                            $(_this).trigger('focus');
                        }));
                        $(_this).val().length != 0 && $imitate.hide();
                        if (options.onInput) {
                            //绑定oninput/onpropertychange事件
                            var inputChangeEvent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange';
                            $(_this).bind(inputChangeEvent, function () {
                                $imitate[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block';
                            });
                        } else {
                            $(_this).focus(function () {
                                $imitate.hide();
                            }).blur(function () {
                                    /^$/.test($(_this).val()) && $imitate.show();
                            });
                        }
                    }
                }
            });
            return this;
        }
    });
})(jQuery);

/**
 * 文本域自动高度
 */
(function($){
	$.fn.textareaAutoHieght = function(options) {
    var defaults={
      maxHeight:null,
      minHeight:$(this).attr('rows') * 18
    };
    var opts = $.extend({},defaults,options);
    return $(this).each(function() {
      $(this).bind("paste cut keydown keyup focus blur",function(){
        var height,style=this.style;
        this.style.height = opts.minHeight + 'px';
        if (this.scrollHeight > opts.minHeight) {
          if (opts.maxHeight && this.scrollHeight > opts.maxHeight) {
            height = opts.maxHeight;
            style.overflowY = 'scroll';
          } else {
            height = this.scrollHeight;
            style.overflowY = 'hidden';
          }
          style.height = height + 'px';
        }
      }).trigger("blur");
    });
  };
})(jQuery);
